package cn.chendd.cofig.predicates;

import com.google.common.collect.Lists;
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.server.ServerWebExchange;

import java.util.List;
import java.util.function.Predicate;

/**
 * url包含特定文本的请求过滤，若url请求中包含了配置的子url（不区分大小写），符合则进行过滤
 *
 * @author chendd
 * @date 2022/12/25 19:43
 */
@Component
public class UrlContainsRoutePredicateFactory extends AbstractRoutePredicateFactory<UrlContainsRoutePredicateFactory.Config> {

    public UrlContainsRoutePredicateFactory() {
        super(Config.class);
    }

    @Override
    public Predicate<ServerWebExchange> apply(Config config) {

        return serverWebExchange -> {
            String path = serverWebExchange.getRequest().getPath().toString();
            List<String> values = config.getValues();
            for (String value : values) {
                if (path.matches(value) || path.equalsIgnoreCase(value)) {
                    return true;
                }
            }
            return false;
        };
    }

    /**
     * 设置参数映射的数据类型：List<String>
     * @return 数据类型
     */
    @Override
    public ShortcutType shortcutType() {
        return ShortcutType.GATHER_LIST;
    }

    /**
     * 设置配置的参数值与属性名称的映射
     * @return 属性集合
     */
    @Override
    public List<String> shortcutFieldOrder() {
        return Lists.newArrayList("values");
    }

    @Validated
    public static class Config {

        /**
         * 参数值
         */
        private List<String> values;

        public List<String> getValues() {
            return values;
        }

        public void setValues(List<String> values) {
            this.values = values;
        }
    }

}
